package com.zjyc.javaweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjyc.javaweb.domain.po.User;
import com.zjyc.javaweb.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/getAll")
    public String getAll(Model model, String name){
        List<User> userList = userService.getAllUser();
        model.addAttribute("userList", userList);
        model.addAttribute("name", name);
        return "demo/User";
    }

    @GetMapping("/add")
    @ResponseBody
    public int addUser(Model model, User user){
        User user1 = new User(null, "202383020424", "杨崇宝", "123", 18, "man.png", 100);
        user.setPhoto("successful.png");
        return userService.addUser(user1);
    }

    @GetMapping("/getAllUserByMyBatis")
    @ResponseBody
    public String getAllUserByMyBatis(String name,
                                      @RequestParam(value = "pageNumber", defaultValue = "1") int pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "5") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.getAllUserByMyBatis(name);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        List<User> rows = pageInfo.getList();
        int total = (int) pageInfo.getTotal();
        JSONObject result = new JSONObject();
        result.put("rows", rows);
        result.put("total", total);
        return result.toJSONString();
    }

    @RequestMapping("/showUserByBootstrap")
    public String showUserByBootstrap(){
        return "demo/datas";
    }
}
